package com.jeequan.jeepay.pay.router.strategy;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.entity.MchPayPassage;
import com.jeequan.jeepay.core.entity.MchPayRoute;
import com.jeequan.jeepay.pay.model.MchAppConfigContext;
import com.jeequan.jeepay.pay.router.PassageInfo;
import com.jeequan.jeepay.pay.router.RouteStrategy;
import com.jeequan.jeepay.pay.rqrs.payorder.UnifiedOrderRQ;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 费率策略
 * 配置json格式为:
 * {"feePriority": "highest"}
 * 其中value可取highest/lowest
 * @author wxj
 * 2024/10/24
 */
@Service
public class FeeRouteStrategy implements RouteStrategy {

    @Override
    public MchPayPassage route(MchAppConfigContext mchAppConfigContext, UnifiedOrderRQ bizRQ, MchPayRoute mchPayRoute, Map<String, PassageInfo> channelInfoMap) {
        JSONObject jsonObject = JSONObject.parseObject(mchPayRoute.getStrategyParams());
        String feePriority = jsonObject.getString("feePriority");
        List<PassageInfo> list;
        if ("highest".equals(feePriority)) {
            list = channelInfoMap.values().stream()
                    .sorted(Comparator.comparing((PassageInfo a) -> a.getMchPayPassage().getRate()).reversed())
                    .collect(Collectors.toList());
        } else {
            list = channelInfoMap.values().stream()
                    .sorted(Comparator.comparing(a -> a.getMchPayPassage().getRate()))
                    .collect(Collectors.toList());
        }
        return list.get(0).getMchPayPassage();
    }
}
